//
//  MouoSinaMenuView.m
//  WJSinaHomeMenu
//
//  Created by tqh on 2019/5/16.
//  Copyright © 2019 tqh. All rights reserved.
//

#import "MouoSinaMenuView.h"
#import "HexColors.h"
#import "UIView+Extension.h"
#import "MouoSinaMenuToolView.h"
#import "MouoSinaMenuItemCell.h"
#import "MouoSinaMenuItemSection.h"

@interface MouoSinaMenuView()<UICollectionViewDataSource,UICollectionViewDelegate,MouoSinaMenuItemCellDelegate,MouoSinaMenuToolViewDelegate>
{
    //被拖拽的item
    MouoSinaMenuItemCell *_dragingItem;
    //正在拖拽的indexpath
    NSIndexPath *_dragingIndexPath;
    //目标位置
    NSIndexPath *_targetIndexPath;
}

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *dataArray;     //使用的数据
@property (nonatomic,strong) NSMutableArray *unUsedataArray;//没有数据
@property (nonatomic,assign) BOOL canEdit;  //是否能编辑
@property (nonatomic,strong) MouoSinaMenuToolView *toolView;
@property (nonatomic,copy) NSString *title;
@property (nonatomic,assign) BOOL isChange;
@property (nonatomic,assign) NSInteger pageIndex;
@property (nonatomic,assign) BOOL isPageIndexDraging;
- (void)reloadData;

@end

@implementation MouoSinaMenuView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self createView];
        [self addDragingEvent];
        self.alpha =0;
        self.y = - self.height;
    }
    return self;
}


- (void)addMenuWithInUseTitle:(NSArray *)inUseTitle unUseTitle:(NSArray *)unUseTitle {
    self.dataArray = [NSMutableArray arrayWithArray:inUseTitle];
    self.unUsedataArray = [NSMutableArray arrayWithArray:unUseTitle];
    [self reloadData];
}

- (void)showMenuWithTitle:(NSString *)title {
    self.title = title;
    [self showMenu];
}

- (void)showMenuWithIndex:(NSInteger)index {
    self.pageIndex = index;
    [self showMenu];
    [self reloadData];
}

#pragma mark - private

- (void)showMenu {
    [UIView animateWithDuration:0.3 animations:^{
        self.y = 0;
        self.alpha = 1;
    }completion:^(BOOL finished) {
    }];
}

- (void)closeMenu {
  
    //重置状态
    self.canEdit = NO;
    [self.toolView resetData];
    [self.collectionView reloadData];
    [UIView animateWithDuration:0.3 animations:^{
        self.y = -self.height;
        self.alpha = 0;
    }completion:^(BOOL finished) {
    }];
  
}

- (void)reloadData {
    [self.collectionView reloadData];
}

-(void)rearrangeInUseTitles
{
    id obj = [self.dataArray objectAtIndex:_dragingIndexPath.row];
    [self.dataArray removeObject:obj];
    [self.dataArray insertObject:obj atIndex:_targetIndexPath.row];
}

#pragma mark - 创建视图

- (void)createView {
    
    MouoSinaMenuToolView *toolView = [[MouoSinaMenuToolView alloc]initWithFrame:CGRectMake(0, 0, self.width, 50)];
    toolView.delegate = self;
    [self addSubview:toolView];
    self.toolView = toolView;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(74+2, 30+10);
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 3;

    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, toolView.maxY, self.width, self.height - 50-10) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor clearColor];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.contentInset = UIEdgeInsetsMake(0, 15, 0, 15);
    [collectionView registerClass:[MouoSinaMenuItemCell class] forCellWithReuseIdentifier:@"cellID"];
    [collectionView registerClass:[MouoSinaMenuItemSection class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"cellHeader"];
    [self addSubview:collectionView];
    self.collectionView = collectionView;
    
}

- (void)addDragingEvent {
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
    longPress.minimumPressDuration = 0.3f;
    [self.collectionView addGestureRecognizer:longPress];
    
    _dragingItem = [[MouoSinaMenuItemCell alloc] initWithFrame:CGRectMake(0, 0, 74+10, 30+10)];
    _dragingItem.hidden = true;
    [self.collectionView addSubview:_dragingItem];
}

#pragma mark - 事件监听

-(void)longPressMethod:(UILongPressGestureRecognizer*)gesture{
    if (!self.canEdit) {
        return;
    }
    CGPoint point = [gesture locationInView:_collectionView];
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            [self dragBegin:point];
            break;
        case UIGestureRecognizerStateChanged:
            [self dragChanged:point];
            break;
        case UIGestureRecognizerStateEnded:
            [self dragEnd];
            break;
        default:
            break;
    }
}


//拖拽开始 找到被拖拽的item
-(void)dragBegin:(CGPoint)point{
  
    _dragingIndexPath = [self getDragingIndexPathWithPoint:point];
    if (!_dragingIndexPath) {return;}
    [_collectionView bringSubviewToFront:_dragingItem];
    MouoSinaMenuItemCell *item = (MouoSinaMenuItemCell*)[_collectionView cellForItemAtIndexPath:_dragingIndexPath];
    item.isMoving = true;

    //更新被拖拽的item
    _dragingItem.hidden = false;
    _dragingItem.frame = item.frame;
    _dragingItem.title = item.title;
    [_dragingItem setTransform:CGAffineTransformMakeScale(1.1, 1.1)];
}

//正在被拖拽、、、
-(void)dragChanged:(CGPoint)point{
    if (!_dragingIndexPath) {return;}
    _dragingItem.center = point;
    _targetIndexPath = [self getTargetIndexPathWithPoint:point];
    //交换位置 如果没有找到_targetIndexPath则不交换位置
    if (_dragingIndexPath && _targetIndexPath) {
        //更新数据源
        [self rearrangeInUseTitles];
        //更新item位置
        [_collectionView moveItemAtIndexPath:_dragingIndexPath toIndexPath:_targetIndexPath];
        _dragingIndexPath = _targetIndexPath;
    }
}

//拖拽结束
-(void)dragEnd{
    if (!_dragingIndexPath) {return;}
    CGRect endFrame = [_collectionView cellForItemAtIndexPath:_dragingIndexPath].frame;
    [_dragingItem setTransform:CGAffineTransformMakeScale(1.0, 1.0)];
    __weak typeof(_dragingItem) weakDragingItem = _dragingItem;
     __weak typeof(_collectionView) weakCollectionView = _collectionView;
    __weak typeof(_dragingIndexPath) weakDragingIndexPath = _dragingIndexPath;
    __weak typeof(self) myself = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakDragingItem.frame = endFrame;
    }completion:^(BOOL finished) {
        weakDragingItem.hidden = true;
        MouoSinaMenuItemCell *item = (MouoSinaMenuItemCell*)[weakCollectionView cellForItemAtIndexPath:weakDragingIndexPath];
         item.isMoving = false;
        
    
        if (item.isPageIndex) {
            myself.pageIndex = weakDragingIndexPath.row;
            [weakCollectionView reloadData];
        }
       
    }];
    self.isChange = YES;
}

#pragma mark -
#pragma mark 辅助方法

//获取被拖动IndexPath的方法
-(NSIndexPath*)getDragingIndexPathWithPoint:(CGPoint)point{
    NSIndexPath* dragIndexPath = nil;
    //最后剩一个怎不可以排序
    if ([_collectionView numberOfItemsInSection:0] == 1) {return dragIndexPath;}
    for (NSIndexPath *indexPath in _collectionView.indexPathsForVisibleItems) {
        //下半部分不需要排序
        if (indexPath.section > 0) {continue;}
        //在上半部分中找出相对应的Item
        if (CGRectContainsPoint([_collectionView cellForItemAtIndexPath:indexPath].frame, point)) {
            if (indexPath.row != 0) {
                dragIndexPath = indexPath;
            }
            break;
        }
    }
    return dragIndexPath;
}

//获取目标IndexPath的方法
-(NSIndexPath*)getTargetIndexPathWithPoint:(CGPoint)point{
    NSIndexPath *targetIndexPath = nil;
    for (NSIndexPath *indexPath in _collectionView.indexPathsForVisibleItems) {
        //如果是自己不需要排序
        if ([indexPath isEqual:_dragingIndexPath]) {continue;}
        //第二组不需要排序
        if (indexPath.section > 0) {continue;}
        //在第一组中找出将被替换位置的Item
        if (CGRectContainsPoint([_collectionView cellForItemAtIndexPath:indexPath].frame, point)) {
            if (indexPath.row != 0) {
                targetIndexPath = indexPath;
            }
        }
    }
    return targetIndexPath;
}

#pragma mark - <MouoSinaMenuToolViewDelegate>

- (void)mouoSinaMenuToolViewDidEdit:(BOOL)edit {
    self.canEdit = edit;
    [self.collectionView reloadData];
}

- (void)mouoSinaMenuToolViewDidClose {
    [self closeMenu];
    if (self.isChange) {
        self.isChange = NO;
        if (self.delegate && [self.delegate respondsToSelector:@selector(mouoSinaMenuViewDidDoneWithinUseTitles:unUseTitles:index:)]) {
            [self.delegate mouoSinaMenuViewDidDoneWithinUseTitles:self.dataArray unUseTitles:self.unUsedataArray index:self.pageIndex];
        }
    }
}

#pragma mark - <MouoSinaMenuItemCellDelegate>

- (void)mouoSinaMenuItemCellDidCell:(MouoSinaMenuItemCell *)cell {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    //只剩一个的时候不可删除
    if ([_collectionView numberOfItemsInSection:0] == 1) {return;}
    //第一个不可删除
    if (indexPath.row  == 0) {return;}
    cell.isEdit = NO;
    
    id obj = [self.dataArray objectAtIndex:indexPath.row];
    [self.dataArray removeObject:obj];
    [self.unUsedataArray insertObject:obj atIndex:0];
    if (cell.isPageIndex) {
        if (self.pageIndex+1<self.dataArray.count) {
            self.pageIndex+=1;
        }else {
            self.pageIndex = self.dataArray.count-1;
        }
        [_collectionView reloadData];
    }else {
        [_collectionView moveItemAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    }
   
    self.isChange = YES;
}

#pragma mark -<UICollectionViewDataSource,UICollectionViewDelegate>

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return  CGSizeMake([UIScreen mainScreen].bounds.size.width,47);
    }else{
        return  CGSizeMake([UIScreen mainScreen].bounds.size.width,0);
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MouoSinaMenuItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.title = self.dataArray[indexPath.row];
        if (self.pageIndex == indexPath.row) {
            cell.isPageIndex = YES;
        }else {
            cell.isPageIndex = NO;
        }
        if (indexPath.row == 0) {
            cell.isEdit = NO;
        }else {
            cell.isEdit = self.canEdit;
        }
    }else {
        cell.title = self.unUsedataArray[indexPath.row];
        cell.isEdit = NO;
        cell.isPageIndex = NO;
    }
    cell.delegate = self;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    MouoSinaMenuItemSection *section = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"cellHeader" forIndexPath:indexPath];
    return section;
};

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return section == 0 ? self.dataArray.count : self.unUsedataArray.count;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        MouoSinaMenuItemCell *cell = (MouoSinaMenuItemCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        if (!cell.isEdit) {
            [self closeMenu];
            if (self.isChange) {
                self.isChange = NO;
                if (self.delegate && [self.delegate respondsToSelector:@selector(mouoSinaMenuViewDidDoneWithinUseTitles:unUseTitles:index:)]) {
                    [self.delegate mouoSinaMenuViewDidDoneWithinUseTitles:self.dataArray unUseTitles:self.unUsedataArray index:indexPath.row];
                }
            }else {
                if (self.delegate && [self.delegate respondsToSelector:@selector(mouoSinaMenuViewDidIndex:)]) {
                    [self.delegate mouoSinaMenuViewDidIndex:indexPath.row];
                }
            }
        }
    }else{
        MouoSinaMenuItemCell *cell = (MouoSinaMenuItemCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        if (self.canEdit) {
            cell.isEdit = YES;
        }
        id obj = [self.unUsedataArray objectAtIndex:indexPath.row];
        [self.unUsedataArray removeObject:obj];
        [self.dataArray addObject:obj];
        [_collectionView moveItemAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0]];
        self.isChange = YES;
    }
}

@end
